<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>getDerivedStateFromProps</title>
		<!-- 引入react核心库 -->
		<script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
		<!-- 引入react-dom，用于支持react操作DOM -->
		<script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
		<!-- 引入babel，用于解析jsx为js -->
		<script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器 -->
		<div id="test"></div>

		<script type="text/babel">
			/* 
					getDerivedStateFromProps有什么用？
						粗略的说（官网）：state 的值在任何时候都取决于 props
						详细的说：
								1.可以完成：直接复制 props 到 state 上；
								2.可以完成：经过一些逻辑比较了props和state，然后决定是否去更新state
				*/	
			class Demo extends React.Component{

				constructor(props){
					console.log('---constructor---')
					super(props)
					this.state = {sum:50}
				}

				render(){
					console.log('---render---')
					return (
						<div>
							<h2>当前求和为：{this.state.sum}</h2>
							<button onClick={this.add}>+</button>
						</div>
					)
				}

				componentDidMount(){
					console.log('---componentDidMount---')
				}

				static getDerivedStateFromProps(props,state){
					console.log('---getDerivedStateFromProps---',props,state)
					const {n} = props
					const {sum} = state
					if(sum+n === 250) return {sum:0}
					else return null
				}

				add = ()=>{
					const {sum} = this.state
					this.setState({sum:sum+1})
				}
			}

			ReactDOM.render(<Demo n={200}/>,document.getElementById('test'))
		</script>
	</body>
</html>